#1. 导入所需要的包，初始设置plt参数
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Bidirectional
from sklearn.neural_network import MLPRegressor
from scipy.ndimage import gaussian_filter1d
from scipy.signal import medfilt
import math
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from model import LSTM_, result, split_data, turn_back
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from numpy import array
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus']=False
font = {'family': 'Arial','weight': 'normal','size': 10}
plt.rc('font', **font)

#2. 载入数据文件，数据预处理(归一化+划分数据集)
dataset = pd.read_csv('newshuju.csv',usecols=['Internet traffic data'])



n_timestamp = 100
train_days = 620
testing_days = 265
train_set = dataset[0:train_days].reset_index(drop=True)
test_set = dataset[train_days: train_days+testing_days].reset_index(drop=True)
training_set = train_set.iloc[:, 0:].values
testing_set = test_set.iloc[:, 0:].values

sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set)
testing_set_scaled = sc.fit_transform(testing_set)
X_train, y_train = split_data(training_set_scaled, n_timestamp)
X_test, y_test = split_data(testing_set_scaled, n_timestamp)

X_train = (X_train.reshape(X_train.shape[0], X_train.shape[1] * X_train.shape[2]))
X_test = (X_test.reshape(X_test.shape[0], X_test.shape[1] * X_test.shape[2]))

clf = MLPRegressor(max_iter=10,hidden_layer_sizes=(100),random_state=0)
clf.fit(X_train,y_train)

y_predicted = clf.predict(X_test)
y_test_descaled, y_predicted_descaled = turn_back(y_test, y_predicted, sc, training_set_scaled)
np.savez('result/bp_result.npz', true=y_test_descaled, pred=y_predicted_descaled)
result(y_test_descaled, y_predicted_descaled, 'BP')
rmse = np.sqrt(mean_squared_error(y_test_descaled, y_predicted_descaled))
r2 = r2_score(y_test_descaled, y_predicted_descaled)
print("RMSE=" + str(round(rmse,4)))#保留两位小数
print("r2=" + str(round(r2,4)))
plt.figure()
plt.plot(y_test_descaled, c='r', label='real')
plt.plot(y_predicted_descaled, c='b', label='pred')
plt.legend()
plt.xlabel('Timing Points')
plt.ylabel('Value')
plt.savefig('figure/BP预测结果.jpg',dpi=600)
plt.show()

result(y_test_descaled, y_predicted_descaled, 'BP')
rmse = np.sqrt(mean_squared_error(y_test_descaled, y_predicted_descaled))
r2 = r2_score(y_test_descaled, y_predicted_descaled)
print("RMSE=" + str(round(rmse,4)))#保留两位小数
print("r2=" + str(round(r2,4)))
